﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using DbTaglio.SvcLayer;
using DbTaglio.SvcLayer.DbTaglioService;
using System.Runtime.Serialization; 

namespace Gucci.DbTaglio.Site.Wp.Diagnostica_dbtWp
{
    [ToolboxItem(false)]
    public partial class Diagnostica_dbtWp : System.Web.UI.WebControls.WebParts.WebPart
    {

        private string _domain ="";
        private string _spGroupAdmins = "DbTaglioSPAdmins";
        private string _winGroupAdmins = "DbTaglioAdmins";

        string _idargs = "", _descrizione = "", _codice = "", _codMateriale = "", _spUserName = "";
        DBTWinLogin _loginUserData = null;
        SPUser _spUser = null;
        bool _isAbilitatoAlConsumo = false, _isAdmin = false;

        # region LOGIN - DATI UTENTE

        DBTManager _manager = null;

        private string getSPuser()
        {
            _spUser = SPContext.Current.Web.CurrentUser;

            var arr = _spUser.Name.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
            if (arr != null && arr.Length > 1)
                _spUserName = arr[1];

            return _spUserName;
        }

        #endregion


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();

            _domain = Environment.UserDomainName;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            _manager = new DBTManager(getSPuser());
            var result = _manager.EnsureLogin(HiddenCodiceFornitore.Value, HiddenIsAdmin.Value);

            if (result.HaErrori)
            {
                LabelErrori.Text = result.Eccezione.Message;
                return;
            }

            var web = SPContext.Current.Web ;

            LabelEnviron.Text = 
                string.Format( "Domain: {0} - Environ User: {1} ",Environment.UserDomainName , Environment.UserName ); 

            SPUser user = web.CurrentUser;
            string userName = " SP Login name : "+ user.LoginName + " || SP Name : " + user.Name;
            LabelUser.Text = userName;
  
            var userGroups = user.Groups;            
            foreach (SPGroup gruppo in userGroups)
            {
                LabelGroups.Text += gruppo.Name + "\r\n";
            }

            LabelGroups.Text += "\r\n User is in SP GROUPS :\r\n";
           
            var siteGroups = web.SiteGroups ;
            foreach (SPGroup gruppo in siteGroups)
            {
                var yes = gruppo.ContainsCurrentUser;
                var users = gruppo.Users;

                if(yes)
                    LabelGroups.Text += gruppo.Name + ", ";

            }


            //SPGroup adminDbTaglioGroup = siteGroups[_spGroupAdmins];

            
            //if (adminDbTaglioGroup != null)
            //{
            //    LabelIsInDbTSpAdminGroups.Text =
            //                 adminDbTaglioGroup.ContainsCurrentUser.ToString();
            //}
            //else
            //    LabelIsInDbTSpAdminGroups.Text = "Error";


            try
            {
                callHelloWcf();
            }
            catch { }


            try
            {
                callVari();
             }
            catch { }

        }


        private void callVari()
        {
            //fase 1 Commesse
            var filter = new CommessaSearchModel();
            var commesse = _manager.ProxyGetWcf.getCommesse(filter, true);
            _manager.setDropDown(commesse, DropCommesse, "TestataCommessa", "", LabelErrori);

            
            //fase 2 Terzisti
            var terzisti = _manager.ProxyGetWcf.getTerzisti(true);
            _manager.setDropDown(terzisti, DropTerzisti, "RagioneSocialeTerzista", "CodiceTerzista", LabelErrori);
  

           //fase 3  Stagioni
           var stagioni = _manager.ProxyGetWcf.getStagioni(true);
           _manager.setDropDown(stagioni, DropStagioni, "StagioneId", "StagioneId", LabelErrori);


           //fase 4 Master Items
           var masterit = _manager.ProxyGetWcf.getMasterItems(new ItemSearchModel(), true);
           _manager.setDropDown(masterit, DropMasterItems, "ItemDisplayName", "ItemId", LabelErrori);

            //fase 5 get Taglie del master item
           if (!masterit.HaErrori)
           {
               var mItem1 = masterit.Dati.FirstOrDefault();
               if (mItem1 != null)
               {
                   var taglie = _manager.ProxyGetWcf.getMasterItemTaglie(mItem1);
                   _manager.setDropDown(taglie, DropTaglieMaster, "DescrizioneTaglia", "ItemId", LabelErrori);
               }
               else
                   LabelErrori.Text += "\r\nErrore GetMasterItemTaglie : " + " Item 1 non trovato";
           }


            // Materiali
           //fase 4 Master Items
           var materiali = _manager.ProxyGetWcf.getMasterItems(new ItemSearchModel(), true);
           _manager.setDropDown(materiali, DropMasterItems, "ItemDisplayName", "ItemId", LabelErrori);

   
        }//fM

        /// METODI VARI
        
        private void callHelloWcf()
        {
            // "Diego", "Pa$$w0rd1"
            var wcf = new MetGet(null,null, true);
            var result = wcf.tryHelloWcf();

            if (result.HaErrori)
                LabelHelloWcf.Text = result.Eccezione.Message;
            else
                LabelHelloWcf.Text = result.Dati;


            try
            {
                var winUs = wcf.GetWinUserName();
                LabelWinUser.Text =
                    string.Format("WinUser User > : {0} \r\n",
                    winUs.HaErrori ? winUs.Eccezione.Message : winUs.Dati);
            }
            catch { }


            try
            {


                var winServ = wcf.GetDBTWinAndAppLogin(_spUserName);
            string res="";
            if (!winServ.HaErrori)
                LabelServiceUser.Text =
                     string.Format(@"WinUserName:{0} - EnvUserName: {1} - SpUserName: {2} - AppUserName: {3}
                        \r\IsAuthenticated: {4}  - AuthenticationType: {5} - ImpersonationLevel: {6}
                         \r\nGroups: {7}\r\n- 
                         IsInDbTaglioAdminGroup: {8} - IsInDbTaglioUsersGroup: {9}\r\n
                            ",
                     winServ.Dati.WinUserName,winServ.Dati.EnvUserName,  _spUserName , winServ.Dati.AppUserName,
                     winServ.Dati.IsAuthenticated.ToString(), winServ.Dati.AuthenticationType, winServ.Dati.ImpersonationLevel ,
                     winServ.Dati.MemberOfWinGroups.Aggregate((s1,s2)=>  s2 += s1  )  ,
                     winServ.Dati.IsInDbTaglioAdminGroup ,
                     winServ.Dati.IsInDbTaglioUsersGroup                    
                     );
            else
                LabelServiceUser.Text = string.Format("Errori : {0}", winServ.Eccezione.Message);

            }
            catch(Exception ex) 
            {
                LabelServiceUser.Text = string.Format("Errori : {0}", ex.Message);
            }

        }

  


        private void setDropDown(object pDati,  DropDownList pDrop, string pTextField,string pValueField)
        {
            pDrop.DataTextField = pTextField;
            pDrop.DataValueField = pValueField;
            pDrop.DataSource = pDati;
            pDrop.DataBind();
        }


    }//fC
}
